<!doctype html>
<html>
  <head>
    <title>Notifications: Action reflection in the "notificationclick" event.</title>
    <script src="../resources/testharness.js"></script>
    <script src="../resources/testharnessreport.js"></script>
    <script src="../serviceworker/resources/test-helpers.js"></script>
    <script src="resources/test-helpers.js"></script>
  </head>
  <body>
    <script>
      // Tests that the action property of the "notificationclick" event in the
      // Service Worker accurately reflects which action was activated, if any.

      async_test(function(test) {
          var scope = 'resources/scope/' + location.pathname;
          var script = 'instrumentation-service-worker.js';
          var port;

          var options = {
              actions: []
          };

          var expectedActions = [];
          for (var i = 0; i < Notification.maxActions; ++i) {
              var action = { action: 'action' + i, title: 'Action ' + i };
              options.actions.push(action);
              expectedActions.push(action.action);
          }
          // Expect empty string when main body of notification is activated.
          expectedActions.push('');

          testRunner.setPermission('notifications', 'granted', location.origin, location.origin);
          getActiveServiceWorkerWithMessagePort(test, script, scope).then(function(info) {
              port = info.port;
              // (1) Tell the Service Worker to display a Web Notification.
              return sendCommand(port, {
                  command: 'show',

                  title: scope,
                  options: options
              });
          }).then(function(data) {
              // (2) Confirm that the service worker displayed the notification successfully.
              assert_true(data.success, 'The notification must have been displayed.');

              // (3) Simulate a click on each button and on the notification body.
              for (var i = 0; i < options.actions.length; ++i)
                  testRunner.simulateWebNotificationClick(scope, i);
              testRunner.simulateWebNotificationClick(scope);

              port.addEventListener('message', function(event) {
                  // (4) Listen for confirmation from the Service Worker that the
                  // notification has been clicked on. Make sure that the action
                  // property set on the NotificationEvent object is as expected.
                  assert_equals(event.data.command, 'click', 'The notification was expected to be clicked.');

                  assert_equals(event.data.action, expectedActions.shift());

                  if (expectedActions.length === 0)
                      test.done();
              });
          }).catch(unreached_rejection(test));

      }, 'NotificationEvent action property should be reflect which action was clicked.');
    </script>
  </body>
</html>
